using Godot;
using System;

public partial class HealthComponent : Node
{
	[Signal] 
	public delegate void DiedEventHandler();
	[Signal]
	public delegate void HealthChangedEventHandler();

	[Export]
	public float maxHealth = 10;
	public float currentHealth;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		currentHealth = maxHealth;
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	//受到伤害
	public void Damage(float damageAmount){
		currentHealth = Math.Max(currentHealth - damageAmount,0);
		this.EmitSignal(nameof(HealthChanged));
		Callable callable = Callable.From(CheckDeath);
		callable.CallDeferred();
	}

	public double GetHealthPercent(){
		if(maxHealth <= 0){
			return 0;
		}
		return Math.Min(currentHealth/maxHealth,1);
	}

	public void CheckDeath(){
		if(currentHealth == 0){
			//怪物死亡
			this.EmitSignal(nameof(Died));//发送死亡信号
			Owner.QueueFree();//Owner 上级，所有者
		}
	}

}
